<template>
  <uni-file-picker
    v-model="internalFileList"
    :fileMediatype="fileMediatype"
    :mode="mode"
    :limit="limit"

    @select="beforeUpload"
    @success="handleSuccess"
    @fail="handleFail"
    @delete="handleDelete"

  />
</template>

<script setup>
import { ref,watch } from 'vue';
import CryptoJS from 'crypto-js';
import request from "@/utils/request.js";
import {
	useUserStore
} from '@/store/index.js'
import {
	getToken
} from '@/utils/token.js'
// 用户仓库
const userStore = useUserStore()
const props = defineProps({
  modelValue: { type: Array, default: () => [] }, // v-model 绑定的值
  limit: { type: Number, default: 10 },
  fileExtname: { type: Array, default: () => ['jpg', 'jpeg', 'gif', 'png'] },
  mode: { type: String, default: 'grid' },
  fileMediatype: { type: String, default: 'image' },
});

const emit = defineEmits(['update:modelValue']);
// 内部文件列表（用于 uni-file-picker）
const internalFileList = ref([]);
// post对象参数
const postObjectParams = ref({});
// 文件名称映射
const fileNameMap = ref({});
// 初始化：将父组件的 modelValue 映射到 internalFileList
watch(() => props.modelValue, (newVal) => {
  internalFileList.value = newVal;
}, { immediate: true });

// 文件选择时触发（相当于beforeAllFilesUpload）
const beforeUpload = async (files) => {
  try {
    // 获取post对象参数
    const result = await request.get('/infra/file/post-object-params');
    postObjectParams.value = result;
    // 生成文件名称映射
    for (const file of files.tempFiles) {
      await uploadFile(file, file.name)
    }
    
    
    // return true;
  } catch (error) {

    uni.showToast({
      title: '获取上传文件参数失败',
      icon: 'error'
    });
    // return false;
  }
};

// 生成文件名称
const generateFileName = async (file) => {
  // 在小程序中，file对象结构可能不同，需要根据实际情况调整
  const filePath = file.path || file.url;
  
  // 读取文件内容
  const arrayBuffer = await getFileArrayBuffer(filePath);
  const wordArray = CryptoJS.lib.WordArray.create(arrayBuffer);
  
  // 计算SHA256
  const sha256 = CryptoJS.SHA256(wordArray).toString();
  
  // 拼接后缀
  const ext = file.name.substring(file.name.lastIndexOf('.'));
  
  return `${sha256}${ext}`;
};

// 获取文件的ArrayBuffer
const getFileArrayBuffer = (filePath) => {
  return new Promise((resolve, reject) => {
    uni.getFileSystemManager().readFile({
      filePath,
      success: (res) => resolve(res.data),
      fail: (err) => reject(err)
    });
  });
};
// 3. 手动上传实现
const uploadFile = async (file, fileName) => {
  const formData = {
    key: `${postObjectParams.value.dir}${fileName}`,
    success_action_status: '200',
    policy: postObjectParams.value.policy,
    'x-oss-signature': postObjectParams.value.signature,
    'x-oss-signature-version': postObjectParams.value.version,
    'x-oss-credential': postObjectParams.value.credential,
    'x-oss-date': postObjectParams.value.ossdate,
    'x-oss-security-token': postObjectParams.value.token,
    // file: file.path, // 小程序中文件路径在 file.path
  };
  uni.uploadFile({
    url: postObjectParams.value.host,
       filePath: file.path,
       formData: formData,
       name: 'file',
        header: {
          "Authorization": `Bearer ${getToken()}`,
},
 success: (res) => {
 console.log(res);
// 4. 上传成功后更新 v-model
  const url = `${postObjectParams.value.host}/${postObjectParams.value.dir}${fileName}`;
   const currentList = Array.isArray(internalFileList.value) ? internalFileList.value : [];
    console.log(props.modelValue,'upload');
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0'); // Months are 0-based
const day = String(today.getDate()).padStart(2, '0');

const uploadTime = `${year}-${month}-${day}`;
  internalFileList.value=[...currentList, {url,name:fileName,response:{url},uploadTime:uploadTime}]
  emit('update:modelValue', internalFileList.value);
    console.log(internalFileList.value,'upload');
},
 fail(err) {
console.log(err);

}})


  
};
// // 上传成功处理
// const handleSuccess = (res) => {
//   const file = res.tempFile;
//   return {
//     url: `${postObjectParams.value.host}/${postObjectParams.value.dir}${fileNameMap.value[file.name]}`
//   };
// };
// 上传成功处理
const handleSuccess = (res) => {
  console.log(res,'res');
};

// 上传失败处理
const handleFail = (error) => {
   console.log("上传失败",error);
  uni.showToast({
    title: '上传失败',
    icon: 'error'
  });
  console.error('上传失败:', error);
};
// 删除处理
const handleDelete = (e) => {
  console.log(e,'e');
  internalFileList.value.splice(e.index,1); 
  console.log(internalFileList.value,'in');
  emit('update:modelValue', internalFileList.value);
}
</script>